# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dmo-compact.  If not, see <http://www.gnu.org/licenses/>.


import os,re,sys
from hashlib import md5
from shutil import copytree as copydir
class element:
	compressed=False
	def __init__(self,path,name,type,newname,opts):
		self.name=name
		self.path=path
		self.type=type
		if opts['-s']:
			self.newname=newname
			self.newname_hash()
		else:
			self.newname = self.name
			
	def newname_hash(self):
		file_hash = md5(open(os.path.join(self.path,self.name), 
					"rb").read()).hexdigest()
		self.newname =self.newname +"-"+file_hash+"."+self.type
		

def compress(element):
	prog = "java -Dfile.encoding=UTF8 -jar yuicompressor-2.2.4.jar "
	if element.type == 'js':
		prog + '--nomunge'  
	args = os.path.join(element.path,element.name)+" -o "+os.path.join(element.path,element.newname)
	os.popen(prog + args)
	
def get_tree(path,js,css,html,opts):
	 
	for root,dirs,files in os.walk(path):
		for name in files:
			file_root = os.path.join(root)
			file_path = os.path.join(root,name)
			js_match=re.match ("(.+?)(\.js)$",name)
			css_match= re.match ("(.+?)(\.css)",name)
			if js_match:
				newname = js_match.group(1)
				js.append(element(file_root,name,"js",newname,opts))
			elif css_match:
				newname = css_match.group(1)
				css.append(element(file_root,name,"css",newname,opts))
			elif re.match ("(.+)(\.html)$",name):
				html.append(file_path)
		
def substitution(html,js,css):
	print "modifiying html sources"	  
	for html_file in html:
		url_dest=html_file+".tmp"
		dest=open(url_dest,'w')
		r=open(html_file,'r')
		
		for line in r:
			for el in js:
				line=re.sub(re.escape(el.name),el.newname,line)
			for el in css:
				regex = re.compile(re.escape(el.name))
				line=re.sub(re.escape(el.name),el.newname,line)
			dest.write(line)
		r.close()
		dest.close()
		os.rename(url_dest,html_file)

def get_options(argv):
	opts={}
	while argv:
		if argv[0][0] == '-':
			if argv[0]=='-h':
				opts[argv[0]] =''
			else:
				opts[argv[0]] = argv[1]
				argv = argv[2:]
		else:
			argv = argv[1:]
	return opts

def main(options):
	if not os.path.exists(options['-i']):
		print "Input directory doesn\'t exist"
		exit()	
	if os.path.exists(options['-o']):
		print options['-o'] + "already exists."
		exit()
 
	copydir(options['-i'],options['-o'])
	
	print "reading the project filetree"
	
	js = []
	css = []
	html = []
	
	get_tree(options['-o'],js,css,html,options)
	
	print "Compressing Javascript files"
	for i in js:
	   compress(i)
	print "Compressing stylesheets"
	for i in css:
	   compress(i)
	
	if options['-s']:
		substitution(html, js, css)
	
def usage():
	print """
	To use the compressor you must give input and output locations.
	options:
		-i	  To give the input directory
		-o	  To set the output directory
		-h	  Prints this help dialog
		-s 	  Substitute files with a hash in name
	dmo-compressor - i inputDirectory  -o outputDirectory	
 """
	return

######### main calls, do not touch this lines
options = get_options(sys.argv)
if options['-s'] == 'true':
	options['-s']=True
else:
	options['-s']=False
	
if len(options) <= 0 or not options['-i'] and not options['-o'] and not options['-h']:
	usage()
	exit() 
main(options)


